#include "convert.h"
#include "ui_convert.h"

Convert::Convert(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Convert)
{
    ui->setupUi(this);

    srcCodec = QTextCodec::codecForName("GBK")    ;
    finalCodec = QTextCodec::codecForName("UTF-8");


    ui->GBK_To_UTF->setChecked(true) ;

    QObject::connect(ui->CancelButton,SIGNAL(clicked()),this,SLOT(CancelButton_Slot())) ;
    QObject::connect(ui->SrcButton,SIGNAL(clicked()),this,SLOT(SrcButton_Slot())) ;
    QObject::connect(ui->FinalButton,SIGNAL(clicked()),this,SLOT(FinalButton_Slot())) ;
    QObject::connect(ui->ConvertButton,SIGNAL(clicked()),this,SLOT(Convert_Slot())) ;
    QObject::connect(ui->GBK_To_UTF,SIGNAL(clicked()),this,SLOT(GBK_To_UTF_Slot())) ;
    QObject::connect(ui->UTF_To_GBK,SIGNAL(clicked()),this,SLOT(UTF_To_GBK_Slot())) ;
}

void Convert::SrcButton_Slot()
{
    sfileName =  QFileDialog::getOpenFileNames(NULL,"Source Files","./","All C++ files (*.cpp *.h);;Text files(*.txt);;binary system(*.wks)") ;

    if(sfileName.size() == 0) return ;

    QFileInfo fileInfo(sfileName[0]) ;
    QString sSourceDir = fileInfo.path() ;

    QString sTemp = QString("%1").arg(sfileName.size()) ;
    ui->Numlabel->setText(sTemp) ;
    ui->SoucePath_Edit->setText(sSourceDir) ;
    ui->CancelButton->setEnabled(false) ;
}

void Convert::FinalButton_Slot()
{
   QString sDir = QFileDialog::getExistingDirectory(NULL,"Finally Files","./"
                                                     ,QFileDialog::ShowDirsOnly|QFileDialog::DontResolveSymlinks) ;

   ui->FinalPath_Edit->setText(sDir) ;
}

void Convert::Convert_Slot()
{

    QString sFinalFileDir;
    sFinalFileDir = ui->FinalPath_Edit->text() ;

    m_pConvert_Thread = new Convert_Thread(sfileName,sFinalFileDir,srcCodec,finalCodec) ;
    m_pConvert_Thread->start() ;
    ui->ConvertButton->setEnabled(false) ;
    QMessageBox::information(this,"show","Convert has Finished") ;
    ui->ConvertButton->setEnabled(true) ;
    ui->CancelButton->setEnabled(true);
}

void Convert::GBK_To_UTF_Slot()
{
    srcCodec = QTextCodec::codecForName("GBK") ;
    finalCodec = QTextCodec::codecForName("UTF-8") ;
}

void Convert::UTF_To_GBK_Slot()
{
    srcCodec = QTextCodec::codecForName("UTF-8") ;
    finalCodec = QTextCodec::codecForName("GBK") ;
}

void Convert::CancelButton_Slot()
{
    m_pConvert_Thread->terminate() ;
    m_pConvert_Thread->wait() ;
    ui->ConvertButton->setEnabled(true) ;
}

Convert::~Convert()
{
    delete m_pConvert_Thread ;
    delete ui ;
}
